import Responsive from '@c/responsive'
import Footer from '@c/footer'
import Image from '@c/image'
import styles from './index.module.scss'
import cm from 'classnames'
import { useState } from 'react'
import { getThisWeekDates, coverPosition } from '@/utils/date'
import { isPureNumber } from '@/utils/utils'
import { getChannels, getProgramList } from '@/api/live'
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import Link from 'next/link'

const getHM = startTime => {
  let time = new Date(startTime * 1000)
  return `${coverPosition(time.getHours())}:${coverPosition(time.getMinutes())}`
}

// 获取直播状态
const getLiveStatus = (startTime, endTime) => {
  const now = new Date().getTime()
  if (now < startTime * 1000) {
    return '未开始'
  } else if (now > endTime * 1000) {
    return '已结束'
  } else {
    return '直播中'
  }
}

const { today, dates } = getThisWeekDates()
const formatChannel = channelList => {
  return channelList.map(item => {
    return {
      ...item,
      time: getHM(item.startTime),
      status: getLiveStatus(item.startTime, item.endTime)
    }
  })
}

const Index = props => {
  const { channelGroup, currChannel, currGroups, channelLists, currChannelGroup } = props
  const [currDay, setCurrDay] = useState(today)
  const [programList, setProgram] = useState([])
  const router = useRouter()

  // 获取节目单数据
  const getProgramData = async data => {
    const res = await getProgramList(data)
    setProgram(res.data ? formatChannel(res.data[data.channelId].programs) : [])
  }
  useEffect(() => {
    if (!currChannel || !currDay) {
      return
    }
    getProgramData({
      date: currDay.replaceAll('-', ''),
      channelId: currChannel.id
    })
  }, [currChannel, currDay])

  // 间隔一分钟轮更数据
  const clearTimer = timer => timer && clearTimeout(timer)
  useEffect(() => {
    let timer = null
    clearTimer(timer)
    timer = setTimeout(() => {
      setProgram(formatChannel(programList))
    }, 1000 * 60)
    return () => clearTimer(timer)
  }, [programList])

  useEffect(() => {
    return () => {
      clearTimer()
      sessionStorage.setItem('lastPage', true)
    }
  }, [])
  const changeChannelGroup = item => {
    setCurrDay(today)
    router.replace(`/live/epg/${channelLists[item][0].url}`)
  }

  return (
    <>
      <Responsive className={styles.container}>
        <div className={styles.classify}>
          {channelGroup.map((item, index) => {
            return (
              <p
                className={cm(styles.item, {
                  [styles.itemActive]: item === currChannelGroup
                })}
                key={index}
                onClick={() => changeChannelGroup(item)}
              >
                {item}
              </p>
            )
          })}
        </div>
        <div className={cm(styles.channels, 'hideWhenPc')}>
          {currGroups &&
            currGroups.map((item, index) => {
              return item.url ? (
                <Link
                  replace
                  href={`/live/epg/${item.url}`}
                  className={cm(styles.item, {
                    [styles.itemActive]: item.id === currChannel.id
                  })}
                  key={index}
                >
                  {item.name.split(' ')[0]}
                </Link>
              ) : null
            })}
        </div>
        <div className={cm(styles.date, styles.datePhone)}>
          {dates.map(item => {
            return (
              <div
                key={item.date}
                className={cm(styles.item, {
                  [styles.itemActive]: item.date === currDay
                })}
                onClick={() => setCurrDay(item.date)}
              >
                <p>{item.text}</p>
                <time>{item.date}</time>
              </div>
            )
          })}
        </div>
        <div className={cm(styles.line, 'hideWhenPhone')}>
          <div className={styles.bg} data-name={currChannel.name}>
            <img loading="lazy" src="/images/epg_bg.png" alt={currChannel.name} />
            <h2 className={styles.h2}>{currChannel.name}</h2>
          </div>
        </div>
        <div className={styles.classifyMain}>
          <div className={cm(styles.left, 'hideWhenPhone')}>
            {currGroups &&
              currGroups.map((item, index) => {
                return item.url ? (
                  <Link
                    replace
                    href={`/live/epg/${item.url}`}
                    className={cm(styles.item, {
                      [styles.itemActive]: item.id === currChannel.id
                    })}
                    key={index}
                  >
                    <Image src={item.img} alt={item.name} className={styles.img} />
                  </Link>
                ) : null
              })}
          </div>
          <div className={cm(styles.right, styles.rightPhone)}>
            {programList.map((item, index) => {
              return (
                <div key={index} className={styles.item}>
                  <div style={{ display: 'flex' }}>
                    <time className={styles.time}>{item.time}</time>
                    <p>{item.name}</p>
                  </div>
                  {item.status === '直播中' ? (
                    <button className={cm(styles.btn, styles.btnLive)}>
                      <div className={styles.liveIcon}>
                        <span></span>
                        <span></span>
                        <span></span>
                      </div>
                      <span>直播中</span>
                    </button>
                  ) : (
                    <button className={styles.btn}>{item.status}</button>
                  )}
                </div>
              )
            })}
          </div>
        </div>
      </Responsive>
      <Footer />
    </>
  )
}

export default Index

const filterChannel = channels => {
  return channels
    .filter(item => channelGroup.includes(item.name))
    .reduce((target, curr) => {
      target[curr.name] = curr.channels
      return target
    }, {})
}
const initChannel = (channelLists, currChannelGroup, channel) => {
  if (channel === 'all') {
    try {
      return channelLists[currChannelGroup].length ? channelLists[currChannelGroup][0] : { id: 75 }
    } catch (error) {
      return { id: 75 }
    }
  }
  return channelLists[currChannelGroup].filter(item => item.url === channel)[0]
}

/**
 * 只需要央视和卫视的频道
 * */
const channelGroup = ['央视', '卫视']
export async function getServerSideProps({ params }) {
  // 暂时隐藏掉节目单
  return { notFound: true }

  const { channel } = params
  if (isPureNumber(channel)) return { notFound: true }

  const res = await getChannels({})
  const channelLists = filterChannel(res?.data?.channelGroups || [])
  const currChannelGroup = channel.includes('cctv') || channel === 'all' ? '央视' : '卫视'
  const currChannel = initChannel(channelLists, currChannelGroup, channel)
  const currGroups = channelLists[currChannelGroup] || []
  return {
    props: {
      channel: params.channel,
      channelGroup,
      channelLists,
      currChannelGroup,
      currChannel,
      currGroups,
      layoutProps: {
        noSomeMetaInfo: false,
        url: '/live/epg/all',
        title: `${currChannel.name}节目表 - 电视直播 - 星视界`,
        desc: `提供${currChannel.name}本周节目时间表，查看节目播出时间，锁定频道精彩内容！`
      }
    }
  }
}
